package com.naizhuai;

import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.naizhuai.Model.AccountHelper;
import com.naizhuai.Model.ModelProvider;
import com.naizhuai.Model.db.user.PersonUserBean;
import com.naizhuai.Model.db.user.UserDataSourse;
import com.naizhuai.network.NetWorkObserver;
import com.naizhuai.network.apistore.apistoreiml.CommonManagerIml;
import com.naizhuai.ui.BaseActivity;
import com.naizhuai.ui.components.NavTabView;
import com.naizhuai.ui.entity.Bus.Bus;
import com.naizhuai.ui.entity.QRCodeMsgBean;
import com.naizhuai.ui.entity.QRCodeScanBean;
import com.naizhuai.ui.entity.User.MainPageRedPoint;
import com.naizhuai.ui.home.SearchActivity;
import com.naizhuai.ui.management.presenter.CompanyManageDataApiStoreIml;
import com.naizhuai.ui.mianbusiness.setting.ManageScanQRCodeActivity;
import com.naizhuai.ui.msgmanager.MsgManagerActivity;
import com.naizhuai.ui.testunit.ManageTestScanQRCodeActivity;
import com.naizhuai.util.ConstantsState;
import com.naizhuai.util.DialogUtils;
import com.naizhuai.util.IntentUtils;
import com.naizhuai.util.RxBus;
import com.naizhuai.util.ToastCompat;
import com.tencent.bugly.beta.Beta;

import butterknife.BindView;


public class MainActivity extends BaseActivity implements NavTabView.SelectCallBack {
    @BindView(R.id.msg_container)
    FrameLayout imgMsg;
    @BindView(R.id.tv_dot)
    TextView tvDot;
    @BindView(R.id.fag_nav)
    NavTabView mNavBar;
    @BindView(R.id.app_title)
    TextView appTitle;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.img_search)
    ImageView imgSearch;
    @BindView(R.id.img_qrcode)
    ImageView imgQrcode;
    @BindView(R.id.noticemsg)
    ImageView noticemsg;
    private static final int QRCODE = 200;
    private long mBackPressedTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        InitToolbar();
        mNavBar.config(this, this, getSupportFragmentManager(), R.id.main_container);
        if (!ConstantsState.HAS_START) {
            Beta.checkUpgrade(false, false);
             ConstantsState.HAS_START = true;
        }
    }

    private void InitToolbar() {
        imgSearch.setOnClickListener(v -> {
            tvDot.setVisibility(View.GONE);
            Intent starter = new Intent(this, SearchActivity.class);
            startActivityTransition(starter);
        });
        imgMsg.setOnClickListener(v -> MsgManagerActivity.start(this));

        imgQrcode.setOnClickListener(v ->
                openScanQrCode()
        );
    }

    public void openScanQrCode() {
        IntentUtils.startActivityForResult(this, ManageScanQRCodeActivity.class, QRCODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data == null)
            return;
        switch (requestCode) {
            case QRCODE:
                QRCodeScanBean bean = (QRCodeScanBean) data.getSerializableExtra(QRCodeScanBean.SCAN_DATA_KEY);
                if (bean != null) {
                    requestScan(bean);
                } else
                    shortToast("扫描错误");
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        CommonManagerIml.getInstance().red_point()
                .subscribe(new NetWorkObserver<MainPageRedPoint>() {
                    @Override
                    protected void onFail(String errormsg) {
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(MainPageRedPoint result) {
                        if ("0".equals(result.mainMessageRed)) {
                            tvDot.setVisibility(View.GONE);
                        } else {
                            tvDot.setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    private void requestScan(QRCodeScanBean bean) {
        switch (bean.getJoinType()) {
            case QRCodeMsgBean.USER_JOIN_TYPE:
                break;
            case QRCodeMsgBean.DEPARTMENT_JOIN_TYPE:
                //申请加入部门
                if (TextUtils.isEmpty(AccountHelper.getDepartmentid())) {
                    joinDepartment(bean.getDepartmentId(), bean.getCompanyId());
                } else {
                    DialogUtils.showPromptDialog(this, getString(R.string.already_department));
                }
                break;
            case QRCodeMsgBean.COMPANY_JOIN_TYPE:
                //申请加入公司
                if (TextUtils.isEmpty(AccountHelper.getComPanyid())) {
                    joinComPany(bean.getCompanyId());
                } else {
                    DialogUtils.showPromptDialog(this, getString(R.string.already_company));
                }
                break;
            default:
        }
    }

    private void joinDepartment(String departmentid, String applyCompanyid) {
        showWaitDiaLog();
        CompanyManageDataApiStoreIml.getInstance().requestToJoinCompany(applyCompanyid, departmentid,
                "申请加入部门")
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if (!ConstantsState.isResultOk(result)) {
                            shortToast(getResources().getString(R.string.action_fail));
                        } else {
                            //申请加入公司成功 请等待管理员审核
                            DialogUtils.showPromptDialog(getActivityContext(), getString(R.string.joinDepartmentSuccess_pleasewait));
                        }
                    }
                });
    }

    private void joinComPany(String companyid) {
        showWaitDiaLog();
        CompanyManageDataApiStoreIml.getInstance().requestToJoinCompany(companyid, "",
                "申请加入公司")
                .subscribe(new NetWorkObserver<String>() {
                    @Override
                    protected void onFail(String errormsg) {
                        hideWaitDialog();
                        shortToast(errormsg);
                    }

                    @Override
                    protected void onSuccess(String result) {
                        hideWaitDialog();
                        if (!ConstantsState.isResultOk(result)) {
                            shortToast(getResources().getString(R.string.action_fail));
                        } else {
                            //申请加入公司成功 请等待管理员审核
                            DialogUtils.showPromptDialog(getActivityContext(), getString(R.string.joinCompanySuccess_pleasewait));
                        }
                    }
                });
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void titleChange(String title, String tag) {
        appTitle.setText(title);
        switch (tag) {
            case NavTabView.HOME:
            case NavTabView.ACTION:
            case NavTabView.STUDY:
                showNormalBar();
                break;
            case NavTabView.ME:
                showFullScreen();
                break;
        }
    }


    private void showFullScreen() {
        appTitle.setVisibility(View.GONE);
        imgSearch.setVisibility(View.INVISIBLE);
        imgQrcode.setVisibility(View.VISIBLE);
        noticemsg.setImageResource(R.drawable.noticemsg_white);
        toolbar.setBackgroundColor(getResources().getColor(R.color.nav_orange));
        getImmersionBar().statusBarColor(R.color.nav_orange).init();
    }

    public void showNormalBar() {
        appTitle.setVisibility(View.VISIBLE);
        imgSearch.setVisibility(View.INVISIBLE);
        imgQrcode.setVisibility(View.GONE);
        noticemsg.setImageResource(R.drawable.noticemsg);
        toolbar.setBackgroundDrawable(getResources().getDrawable(R.drawable.headbar));
        getImmersionBar().statusBarColor(R.color.colorPrimary).init();
    }

    @Override
    public void onBackPressed() {
        long curTime = SystemClock.uptimeMillis();
        if ((curTime - mBackPressedTime) < (3 * 1000)) {
            finish();
        } else {
            mBackPressedTime = curTime;
            shortToast(getString(R.string.tip_double_click_exit));
        }
    }

    public static void updateUserData() {
        ModelProvider.provideUserRepository()
                .updateLoginUser(new UserDataSourse.GetUserCallback() {
                    @Override
                    public void onUserLoaded(PersonUserBean user) {
                        RxBus.getDefault().postSticky(new Bus.UserChange());
                    }

                    @Override
                    public void onDataNotAvailable() {
                    }
                });
    }
}